package com.healthcare.cameraview.controller;

import com.healthcare.cameraview.service.FrameProcessorOptimized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/camera")
@CrossOrigin(origins = "*")
public class CameraController {
    private static final Logger logger = LoggerFactory.getLogger(CameraController.class);

    @Autowired
    private FrameProcessorOptimized frameProcessor;

    @PostMapping("/pause")
    public ResponseEntity<Map<String, Object>> pauseCamera() {
        try {
            frameProcessor.pauseCapture();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "摄像头已暂停");
            response.put("status", "paused");
            logger.info("收到暂停摄像头请求");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("暂停摄像头失败: {}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "暂停失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @PostMapping("/resume")
    public ResponseEntity<Map<String, Object>> resumeCamera() {
        try {
            frameProcessor.resumeCapture();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "摄像头已恢复");
            response.put("status", "running");
            logger.info("收到恢复摄像头请求");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("恢复摄像头失败: {}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "恢复失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getCameraStatus() {
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("isPaused", frameProcessor.isPaused());
            response.put("status", frameProcessor.isPaused() ? "paused" : "running");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取摄像头状态失败: {}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
